import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { TypeOrmModule, TypeOrmModuleOptions } from "@nestjs/typeorm";
import { DatabaseName } from "./database.enum";
import { AuditingSubscriber } from "./subscriber/audit.subscriber";

const postgresConfig = (db: string) => {
    return (configService: ConfigService): TypeOrmModuleOptions => ({
        type: "postgres",
        host: configService.get<string>("DATABASE_HOST"),
        port: configService.get<number>("DATABASE_PORT"),
        username: configService.get<string>("DATABASE_USER"),
        password: configService.get<string>("DATABASE_PASSWORD"),
        database: configService.get<string>(db),
        ssl: configService.get<string>("DATABASE_SSL") === "true",
        // entities: [`${__dirname}/entity/*.{ts,js}`],
        autoLoadEntities: true, // 踩坑, 使用 autoLoadEntities 代替 entities 配置, 避免部署后找不到实体的问题
        synchronize: false, // 生产务必关闭, 不建议开启, 启动时会用代码里的实体定义“反向同步”表结构
        logging: configService.get("NODE_ENV") === "development",
        // 不在这里静态声明 subscribers，改为在订阅器构造函数里通过 dataSource.subscribers.push(this) 动态注册
        subscribers: [],
    });
};

@Module({
    imports: [
        TypeOrmModule.forRootAsync({
            useFactory: postgresConfig("DATABASE_DB_DEFAULT"),
            inject: [ConfigService],
        }),
        TypeOrmModule.forRootAsync({
            name: DatabaseName.LOGS, // 连接名称，用于区分多个连接
            useFactory: postgresConfig("DATABASE_DB_LOGS"),
            inject: [ConfigService],
        }),
    ],
    providers: [AuditingSubscriber],
    exports: [],
})
export class DatabaseModule {}
